package com.pengshun.modules.api.order.service.impl;

import com.pengshun.modules.api.coal.repository.MerchantCoalRepository;
import com.pengshun.modules.api.mapper.OrderMapper;
import com.pengshun.modules.api.order.repository.MerchantOrderRepository;
import com.pengshun.modules.api.order.service.MerchantOrderService;
import com.pengshun.modules.api.order.service.dto.MerchantOrderDto;
import com.pengshun.modules.common.BaseResult;
import com.pengshun.modules.common.OrderCommon;
import com.pengshun.modules.domain.MerchantCoal;
import com.pengshun.modules.domain.MerchantOrder;
import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @author luoligang
 * @create 2021/2/20
 */
@Service
@RequiredArgsConstructor
public class MerchantOrderServiceImpl implements MerchantOrderService {


    private final OrderMapper om;
    private final MerchantOrderRepository merchantOrderRepository;
    private final MerchantCoalRepository merchantCoalRepository;
    private  final MessageSource messageSource;


    @Override
    public BaseResult sure(MerchantOrderDto para) throws Exception {
        MerchantOrder order = merchantOrderRepository.findById(para.getOrderId()).orElseGet(MerchantOrder::new);
        //订单状态(1已下单,2用户取消,3商户确认,4商户拒绝，5关闭（24小时），6已支付，7已完成)
        if (order.getOrderStatus().longValue() != OrderCommon.STATEUS_ONE) {
            return new BaseResult(1, messageSource.getMessage("MerchantOrderServiceImpl.sure.status", null, Locale.CHINA));
        }
        BigDecimal freight=para.getFreight()==null?new BigDecimal(0):para.getFreight();
        BigDecimal totalFreight=para.getTotalFreight()==null?new BigDecimal(0):para.getTotalFreight();
        //不是自运  判断运费
        if (!order.getTransportWay().equals(OrderCommon.TRANSPORT_WAY_TWO)) {
            BigDecimal totalFee = order.getNumber().multiply(freight);
            if (totalFee.compareTo(totalFreight) != 0) {
                return new BaseResult(1, messageSource.getMessage("MerchantOrderServiceImpl.sure.compareTo", null, Locale.CHINA));
            }
        }
        //商户确认
        order.setOrderStatus(para.getOrderStatus());
        order.setSureTime(new Date());
        order.setFreight(freight);
        order.setTotalFreight(totalFreight);
        merchantOrderRepository.save(order);
        //添加操作记录
        om.saveOrderRecord(para.getOrderId(), para.getUserId(), para.getOrderStatus(), para.getRemark(), para.getUserName());
        return new BaseResult(0,messageSource.getMessage("MerchantOrderServiceImpl.update.sure.success", null, Locale.CHINA));
    }


    @Override
    public BaseResult selectMerchantOrderList(MerchantOrderDto para) {
        int page = (para.getPage()) * para.getSize();
        List<MerchantOrderDto> list = om.selectMerchantOrderList(para.getUserId(), para.getType(), page < 0 ? 0 : page, para.getSize());
        return new BaseResult(0, list);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult update(MerchantOrderDto para) {
        MerchantOrder order = merchantOrderRepository.findById(para.getOrderId()).orElseGet(MerchantOrder::new);
        String message="";
        if (para.getOrderStatus().equals(OrderCommon.STATEUS_TWO)) {
            message=messageSource.getMessage("MerchantOrderServiceImpl.update.cancle.success", null, Locale.CHINA);
            //订单取消
            if (order.getOrderStatus().longValue() != OrderCommon.STATEUS_ONE && order.getOrderStatus().longValue() != OrderCommon.STATEUS_THREE) {
                return new BaseResult(1, messageSource.getMessage("MerchantOrderServiceImpl.update.status", null, Locale.CHINA));
            }
            order.setCancleTime(new Date());
        }
        if (para.getOrderStatus().longValue() == OrderCommon.STATEUS_FOUR) {
            message=messageSource.getMessage("MerchantOrderServiceImpl.update.back.success", null, Locale.CHINA);
            //商户拒绝
            if (order.getOrderStatus().longValue() != OrderCommon.STATEUS_ONE) {
                return new BaseResult(1, messageSource.getMessage("MerchantOrderServiceImpl.update.status", null, Locale.CHINA));
            }
            order.setBackTime(new Date());
        }

        MerchantCoal coal = merchantCoalRepository.findById(order.getMerchantCoalId()).orElseGet(MerchantCoal::new);
        coal.setCoalNumber(coal.getCoalNumber().add(order.getNumber()));
        //更新库存数量
        merchantCoalRepository.save(coal);
        order.setOrderStatus(para.getOrderStatus());
        order.setCause(para.getCause());
        //更新订单状态原因
        merchantOrderRepository.save(order);
        //记录表添加数据
        om.saveOrderRecord(para.getOrderId(), para.getUserId(), para.getOrderStatus(), para.getCause(), para.getUserName());


        return new BaseResult(0, message);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult delete(MerchantOrderDto para) {
        MerchantOrder order = merchantOrderRepository.findById(para.getOrderId()).orElseGet(MerchantOrder::new);
        if (order.getOrderStatus().equals(OrderCommon.STATEUS_NINE)) {
            return new BaseResult(1,  messageSource.getMessage("MerchantOrderServiceImpl.delete.OrderStatus", null, Locale.CHINA));
        }
        if (!order.getOrderStatus().equals(OrderCommon.STATEUS_TWO) && !order.getOrderStatus().equals(OrderCommon.STATEUS_FOUR) && !order.getOrderStatus().equals(OrderCommon.STATEUS_TEN)) {
            return new BaseResult(1,  messageSource.getMessage("MerchantOrderServiceImpl.delete.status", null, Locale.CHINA));
        }
        order.setOrderStatus(OrderCommon.STATEUS_NINE);
        merchantOrderRepository.save(order);
        om.saveOrderRecord(para.getOrderId(), para.getUserId(), order.getOrderStatus(), "商家删除", para.getUserName());
        return new BaseResult(0,messageSource.getMessage("MerchantOrderServiceImpl.update.delete.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult over(MerchantOrderDto para) {
        MerchantOrder order = merchantOrderRepository.findById(para.getOrderId()).orElseGet(MerchantOrder::new);
        if (!order.getOrderStatus().equals(OrderCommon.STATEUS_SIX)) {
            return new BaseResult(1,  messageSource.getMessage("MerchantOrderServiceImpl.over.status", null, Locale.CHINA));
        }
        order.setOrderStatus(OrderCommon.STATEUS_SEVEN);
        merchantOrderRepository.save(order);
        om.saveOrderRecord(para.getOrderId(), para.getUserId(), order.getOrderStatus(), "商家确认到货", para.getUserName());
        return new BaseResult(0,  messageSource.getMessage("sure.success", null, Locale.CHINA));
    }
}
